﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using IRUM.Core;
using IRUM.XingAPI;
using IRUM.Utils;
using System.Threading;

namespace IRUM.TR
{
    /// <summary>
    /// 기간별 프로그램 매매추이 데이터
    /// </summary>
    public class ProgramTradeData
    {
        public string kind = string.Empty;
        public string gubun = string.Empty;
        public string date = string.Empty;
        public string time = string.Empty;
        public float jisu = 0;
        public float change = 0;
        public long totalSum = 0;
        public long totalBuy = 0;
        public long totalSell = 0;
        public long chaSum = 0;
        public long chaBuy = 0;
        public long chaSell = 0;
        public long bichaSum = 0;
        public long bichaBuy = 0;
        public long bichaSell = 0;
        public long volume = 0;
    }

    public class ProgramTradeDataArgs : EventArgs
    {
        public List<ProgramTradeData> RetData = null;

        public ProgramTradeDataArgs(List<ProgramTradeData> data)
        {
            RetData = data;
        }
    }

    public delegate void ProgramTradeDataHandler(object s, ProgramTradeDataArgs e);

    /// <summary>
    /// 기간별 프로그램 매매추이
    /// </summary>
    public class t1633 : CBaseQuery
    {
        public event ProgramTradeDataHandler OnReceived;
        private List<ProgramTradeData> m_list = new List<ProgramTradeData>();

        private string kind = string.Empty;
        private string lastDBDate = string.Empty;
        private string cts_date = " ";
        private string lastDataDate = string.Empty;

        /// <summary>
        /// 기간별 프로그램 매매추이
        /// <param name="kind">시장구분, K:코스피, D:코스닥</param>
        /// <param name="lastDBDate">DB에 저장된 마지막 날짜</param>
        /// </summary>
        public t1633(string kind, string lastDBDate)
        {
            this.kind = kind;
            this.lastDBDate = lastDBDate;

            SetClassData(TR_Type.t1633);
        }

        public void SetOutBlockData(int Index)
        {
            lastDataDate = m_Query.GetFieldData(m_OutBlock1Name, "date", Index);

            if (Convert.ToInt64(lastDataDate) > Convert.ToInt64(lastDBDate))
            {
                ProgramTradeData pt = new ProgramTradeData();

                pt.kind = kind;
                pt.gubun = "D";
                pt.date = lastDataDate;
                pt.time = "150000";
                pt.jisu = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "jisu", Index));
                pt.change = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "change", Index));
                pt.totalSum = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "tot3", Index));
                pt.totalBuy = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "tot1", Index));
                pt.totalSell = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "tot2", Index));
                pt.chaSum = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "cha3", Index));
                pt.chaBuy = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "cha1", Index));
                pt.chaSell = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "cha2", Index));
                pt.bichaSum = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "bcha3", Index));
                pt.bichaBuy = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "bcha1", Index));
                pt.bichaSell = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "bcha2", Index));
                pt.volume = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "volume", Index));

                int sign = Convert.ToInt32(m_Query.GetFieldData(m_OutBlock1Name, "sign", Index));
                if (sign > 3)
                {
                    pt.change = pt.change * -1;
                }

                m_list.Add(pt);
            }
        }

        public override void HandleQuery()
        {
            int OccursCount = m_Query.GetBlockCount(m_OutBlock1Name);

            for (int OccursIndex = 0; OccursIndex < OccursCount; OccursIndex++)
            {
                try
                {
                    SetOutBlockData(OccursIndex);
                }
                catch (Exception e)
                {
                    Debug.Print(e.ToString());
                    continue;
                }
            }

            //연속조회
            if (m_Query.IsNext == true && Convert.ToInt64(lastDataDate) > Convert.ToInt64(lastDBDate))
            {
                Thread.Sleep(500);
                cts_date = m_Query.GetFieldData(m_OutBlockName, "date", 0);
                RequestNext();
            }
            else
            {
                // 이벤트 발생
                if (OnReceived != null)
                {
                    OnReceived(this, new ProgramTradeDataArgs(m_list));
                }
            }
        }

        protected override void SetRequestData()
        {
            string market = string.Empty;

            switch (kind)
            {
                case "K":           //코스피
                    market = "0";
                    break;
                case "D":           //코스닥
                    market = "1";
                    break;
            }

            m_Query.SetFieldData(m_InBlockName, "gubun", 0, market);                                //시장구분, 1, 0:코스피, 1:코스닥
            m_Query.SetFieldData(m_InBlockName, "gubun1", 0, "0");                                  //금액수량구분, 1, 1:수량, 0:금액
            m_Query.SetFieldData(m_InBlockName, "gubun2", 0, "0");                                  //수치누적구문, 1, 0:수치, 1:누적
            m_Query.SetFieldData(m_InBlockName, "gubun3", 0, "1");                                  //일주월구분, 1, 1:일, 2:주, 3:월
            m_Query.SetFieldData(m_InBlockName, "fdate", 0, "19500101");                            //시작일자, 8
            m_Query.SetFieldData(m_InBlockName, "tdate", 0, DateTime.Today.ToString("yyyyMMdd"));   //종료일자, 8
            m_Query.SetFieldData(m_InBlockName, "gubun4", 0, "0");                                  //직전대비증감구분, 1, 0:Default, 1:직전대비증감
            m_Query.SetFieldData(m_InBlockName, "date", 0, cts_date);                               //연속일자, 8, 처음조회시 space, 연속조회시 outblock의 date
        }
    }
}
